package com.fyy.netty.chapter01.c3;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

/**
 * @Author fyy
 * @Description
 * @Date 2021/4/23 14:17
 */
public class UDPServer {

    public static void main(String[] args) {
        try (DatagramChannel dc = DatagramChannel.open()) {
            dc.socket().bind(new InetSocketAddress(8080));
            dc.configureBlocking(false);

            Selector selector = Selector.open();
            SelectionKey dcKey = dc.register(selector, 0, null);
            dcKey.interestOps(SelectionKey.OP_READ);

            while (true){
                selector.select();
                Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
                while (keys.hasNext()) {
                    SelectionKey key = keys.next();
                    keys.remove();
                    if(key.isReadable()){
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        dc.receive(buffer);
                        buffer.flip();
                        System.out.println(StandardCharsets.UTF_8.decode(buffer));
                        buffer.clear();
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("服务器异常：" + e.getMessage());
        }
    }

}
